//
//  WSSeachDefaulController.m
//  CharonTVProject
//
//  Created by karong on 2023/8/1.
//

#import "WSSeachDefaulController.h"
#import "WSSearchResultController.h"
#import "WSSearchHistoryCell.h"
#import "WSSearchRequest.h"
#import "CTMediator+WSDiscoverAction.h"
#import "WSEqualSpaceFlowLayoutEvolve.h"
#import "WSSearchFootView.h"

@interface WSSeachDefaulController ()<UITextFieldDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, WSSearchResultControllerDelegate, WSSearchFootViewDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *listView;
@property (weak, nonatomic) IBOutlet UIView *searchView;
@property (weak, nonatomic) IBOutlet UITextField *tf;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *listViewTop;

@property (strong ,nonatomic) WSEqualSpaceFlowLayoutEvolve *flowLayout;
@property (strong, nonatomic) NSMutableArray * historyArray;
@property (nonatomic, strong) NSArray * dataArray;

@property (nonatomic, strong) WSSearchResultController * charonTV_searchResultVC;
@end

@implementation WSSeachDefaulController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self layoutListViewTop];
    self.flowLayout = [[WSEqualSpaceFlowLayoutEvolve alloc]initWthType:AlignWithLeft];
    self.flowLayout.betweenOfCell = 12;
    self.flowLayout.inset = 12;
    self.flowLayout.minimumLineSpacing = 12;
    self.listView.collectionViewLayout = self.flowLayout;
    self.tf.tintColor = UIColor.font_yellow_FCB625;
    [self loadSearchHotListcharonTV_searchResultVCRequest];
}

- (void)showcharonTV_searchResultVCResultView {
    self.listView.scrollEnabled = NO;
    [self.listView setContentOffset:self.listView.contentOffset animated:NO];
    if (![self.view.subviews containsObject:self.charonTV_searchResultVC.view]) {
        [self.view addSubview:self.charonTV_searchResultVC.view];
        [self.charonTV_searchResultVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.searchView.mas_bottom);
            make.left.right.bottom.mas_equalTo(self.view);
        }];
    }
    [self.charonTV_searchResultVC searchcharonTV_WithKeyWord:self.tf.text];
}

- (void)layoutListViewTop {
    if (self.historyArray.count > 0) {
        self.listViewTop.constant = 56;
    }
    else {
        self.listViewTop.constant = 0;
    }
    [self.view uploadLayout];
}

- (void)removecharonTV_searchResultVCResultView {
    self.listView.scrollEnabled = YES;
    [self.charonTV_searchResultVC.view removeFromSuperview];
    
}

#pragma mark Result
- (void)loadSearchHotListcharonTV_searchResultVCRequest {
    [WSSearchRequest loadcharonTV_HotSearchSuccess:^(NSArray *array) {
        self.dataArray = array;
        [self.listView reloadData];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

- (IBAction)searchBtnAction:(id)sender {
    if (WSIsNullOrEmpty(self.tf.text)) {
        //返回默認頁面
        [self removecharonTV_searchResultVCResultView];
    }
    else {
        //搜索
        [self.view endEditing:YES];
        [self showcharonTV_searchResultVCResultView];
    }
}

- (void)backAction:(id)sender {
    if ([self.view.subviews containsObject:self.charonTV_searchResultVC.view]) {
        self.tf.text = @"";
        [self removecharonTV_searchResultVCResultView];
    }
    else if(self.navigationController) {
        if (self.navigationController.viewControllers.firstObject == self) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (IBAction)clearHistoryAction:(id)sender {
    [self.historyArray removeAllObjects];
    [self layoutListViewTop];
    [appUserDefaults setValue:self.historyArray forKey:@"searchcharonTV_ResultVChistory"];
    [self.listView reloadData];
    
}

#pragma mark UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (WSIsNullOrEmpty(textField.text)) {
        //返回默認頁面
        [self.charonTV_searchResultVC.view removeFromSuperview];
    }
    else {
        //搜索
        [textField endEditing:YES];
        [self showcharonTV_searchResultVCResultView];
    }
    return YES;
}

#pragma mark UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return MAX(self.historyArray.count, 1);
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    WSSearchHistoryCell * searchHistoryCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WSSearchHistoryCell" forIndexPath:indexPath];
    if (self.historyArray.count > 0) {
        searchHistoryCell.alpha = 1;
        [searchHistoryCell setDataWithString:self.historyArray[indexPath.row]];
    }
    else {
        searchHistoryCell.alpha = 0;
    }
    return searchHistoryCell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGSize size = CGSizeZero;
    if (self.historyArray.count > 0) {
        NSString *text = self.historyArray[indexPath.row];
        CGSize textSize = [text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12]}];
        size.width = MIN(ceil(textSize.width) + 20, kScreenWidth - 24);
        size.height = 26;
    }
    return size;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        WSSearchFootView * charonTV_searchResultVCsearchFootView;
        if (!charonTV_searchResultVCsearchFootView) {
            charonTV_searchResultVCsearchFootView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"WSSearchFootView" forIndexPath:indexPath];
            charonTV_searchResultVCsearchFootView.delegate = self;
            [charonTV_searchResultVCsearchFootView setDataWithObject:self.dataArray];
        }
        return charonTV_searchResultVCsearchFootView;
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    CGSize size = CGSizeZero;
    size.width = WSScreenWidth;
    if (self.dataArray.count > 0) {
        size.height = (36 + 10) * 5;
    }
    return size;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    self.tf.text = self.historyArray[indexPath.row];
    [self showcharonTV_searchResultVCResultView];
}

#pragma mark WSSearchResultControllerDelegate
- (void)searchResultControllerSearchSuccess:(NSString *)keyWord {
    NSInteger index = [self.historyArray indexOfObject:keyWord];
    if (index == NSNotFound) {
        [self.historyArray insertObject:keyWord atIndex:0];
    }
    else {
        [self.historyArray removeObjectAtIndex:index];
        [self.historyArray insertObject:keyWord atIndex:0];
    }
    [self layoutListViewTop];
    [appUserDefaults setValue:self.historyArray forKey:@"searchcharonTV_ResultVChistory"];
    [self.listView reloadData];
}

- (void)searchResultWithKeyWord:(NSString *)keyWord {
    self.tf.text = keyWord;
    [self showcharonTV_searchResultVCResultView];
}
#pragma mark WSSearchFootViewDelegate
- (void)searchFootViewWithObjct:(WSVideo *)object {
    self.tf.text = object.title;
    [self showcharonTV_searchResultVCResultView];
}

- (NSArray *)searchResultControllerHotSearchArray {
    return self.dataArray;
}

- (WSSearchResultController *)charonTV_searchResultVC {
    if (!_charonTV_searchResultVC) {
        _charonTV_searchResultVC = (WSSearchResultController *)[[CTMediator sharedInstance]ct_showcharonTV_SearchResult];
        _charonTV_searchResultVC.delegate = self;
        [self addChildViewController:_charonTV_searchResultVC];
    }
    return _charonTV_searchResultVC;
}

- (NSMutableArray *)historyArray {
    if (!_historyArray) {
        _historyArray = [[NSMutableArray alloc]initWithArray:[[appUserDefaults arrayForKey:@"searchcharonTV_ResultVChistory"] mutableCopy]];
    }
    return _historyArray;
}
@end
